// FrogRenameTruncateDialog.cpp : Implementation of CFrogRenameTruncateDialog

#include "stdafx.h"
#include "FrogRenameTruncateDialog.h"
#include "..\FilerFrogUtils\FilerFrogUtils.h"

// CFrogRenameTruncateDialog
CFrogRenameTruncateDialog::CFrogRenameTruncateDialog(HICON hIcon):
CFrogProgressReportDialog(hIcon),
m_NumCharsToTruncate(0),
m_TruncFromBegining(true),
m_IncludeFileExtension(false),
m_TruncFromBeginingInt(0),
m_IsInitDialog(false)
{
}


LRESULT CFrogRenameTruncateDialog::OnInitDialog(UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled)
{
	CFrogBaseDialog::OnInitDialog(uMsg, wParam, lParam, bHandled);

	HWND spinHwnd = GetDlgItem(IDC_SPIN_TRUNC);
	::SendMessage(spinHwnd, (UINT) UDM_SETRANGE, (WPARAM)0, (LPARAM)MAKELONG((short)UD_MAXVAL, (short)1));

	DoDataExchange(FALSE);

	SetPostPrePreview();

	m_IsInitDialog = true;	

	return 0;
}

LRESULT CFrogRenameTruncateDialog::OnClickedOK(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	bHandled = TRUE;
	// TODO: Add your control notification handler code here
	DoDataExchange(TRUE);
	m_TruncFromBegining = m_TruncFromBeginingInt == 0;

	RunAsyncCommandWithProgressBar(false);
	EndDialog(wID);
	return 0;
}

void CFrogRenameTruncateDialog::ExecuteCommand()
{
	m_FilesRefactor.RenameFilesTruncate(m_LastResult, m_FilesList, m_NumCharsToTruncate, m_TruncFromBegining, m_IncludeFileExtension);
}

LRESULT CFrogRenameTruncateDialog::OnEnChangeConfig(WORD wNotifyCode, WORD wID, HWND hWndCtl, BOOL& bHandled)
{
	if (m_IsInitDialog)
	{
		bHandled = TRUE;
		DoDataExchange(TRUE);
		m_TruncFromBegining = m_TruncFromBeginingInt == 0;

		SetPostPrePreview();
	}

	return 0;
}

void CFrogRenameTruncateDialog::SetPostPrePreview(wstring originalName)
{
	wstring fileName = L"";

	if (m_IncludeFileExtension)
	{
		fileName = originalName;
	}
	else
	{
		fileName = FilerFrogUtils::GetFileNameWithoutExtension(originalName);
	}

	wstring fileExt = FilerFrogUtils::GetFileNameExtension(originalName);

	int len = (int)fileName.length();

	int delta = len - m_NumCharsToTruncate;

	if (delta < 0 || delta > len)
	{
		delta = 0;
	}
	
	wstring newName = L"";

	if (m_TruncFromBegining)
	{
		int location = m_NumCharsToTruncate;

		if (location > len)
		{
			location = len;
		}

		newName = fileName.substr(location);
	}
	else
	{
		newName = fileName.substr(0, delta);	
	}	

	if (!m_IncludeFileExtension)
	{
		newName += L"." + fileExt;
	}

	wchar_t buffer[1024];
	swprintf_s(buffer, 1024, L"Before: %s\r\nAfter: %s", originalName.c_str(), newName.c_str());

	SetDlgItemText(IDC_STATIC_RENAME_PREVIEW, buffer);
}
